package longfly.development;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import longfly.development.Service_manage.MyThread;
import casio.serial.SerialPort;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.StrictMode;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.TranslateAnimation;
import android.widget.AbsoluteLayout;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;

public class Login extends Activity {

	Button  BTN_USER_PASSWORD;
	Button  BTN_USER_NAME;	
	
	Button	BTN_ENTER;
	Button	BTN_ENTER_CARD;
	Button	BTN_QUIT;	
	Button	BTN_QT_SELL;	//前台
	Button	BTN_HT_MANAGE;	//后台
	
	Button BTN_NUM_0;
	Button BTN_NUM_1;
	Button BTN_NUM_2;
	Button BTN_NUM_3;
	Button BTN_NUM_4;
	Button BTN_NUM_5;
	Button BTN_NUM_6;
	Button BTN_NUM_7;
	Button BTN_NUM_8;
	Button BTN_NUM_9;
	Button BTN_NUM_CLEAR;
//	Button BTN_NUM_DEL;
	Button BTN_NAME_DEL;
	Button BTN_PASSWORD_DEL;
	ImageView	BTN_BACK;
	
	private Button	BTN_BACK_DIALOG;
	private Button	BTN_SURE_DIALOG;
	
	private int DIALOG_QUIT = 100;
	private	int	Dispay_widthPixels;
	String num = null ;					
	String password = null ;					
	boolean	SELL_MANAGE = true;
	boolean	NAME_PASSWORD = true;
	
	SQLiteDatabase db;
	private SerialPort mSerialPort = null;		//串口设备描述
	protected OutputStream mOutputStream;		//串口输出描述
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);//强制横屏  
		DisplayMetrics displaysMetrics = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics( displaysMetrics );
        Dispay_widthPixels=displaysMetrics.widthPixels;	//以上是初始化一个UI像素的描述！
/* 
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
        .detectAll()
        .penaltyLog()
        .penaltyDialog() ////打印logcat，当然也可以定位到dropbox，通过文件保存相应的log
        .build());

        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder().detectAll()
        .penaltyLog()
        .build());
*/      
      
		switch (Dispay_widthPixels) {	//根据屏幕的横向像素来加载不通的UI界面！
			case 800:
		        setContentView(R.layout.i800_login);
		        break;
			case 1024:
		        setContentView(R.layout.i800_login);
				break;
			default:
		        setContentView(R.layout.i800_login);
				break;
		}        
        init();
        find_view();
   		BTN_PASSWORD_DEL.setVisibility(View.GONE);		   		
        key_things();
		read_tcp.start();
		tcp_thread.start();
		
        handler = new Handler(){
        	@Override
        	public void handleMessage(Message msg)
        	{
        		if (msg.what == 0x123) {
        			Log.i("info", "handler = " +  msg.obj.toString());
 //       			BTN_ENTER_CARD.append("\n"+ msg.obj.toString());
        			BTN_ENTER_CARD.setText(msg.obj.toString());
				}
        	}
        };
    }

	@Override
	protected void onResume() {
	 /**
	  * 设置为横屏
	  */
	 if(getRequestedOrientation()!=ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE){
	  setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
	 }
	 super.onResume();
	}
	
	private void init() {
		// 用于初始化
		db = SQLiteDatabase.openOrCreateDatabase(this.getFilesDir().toString()+"/Android_POS.db3", null);
		//初始化用户列表
	}

	//查询数据库
	private boolean find_password()
	{
		boolean	Equal;
		String name[] = {BTN_USER_NAME.getText().toString()};
		String User_Password = BTN_USER_PASSWORD.getText().toString();
		try {
    		Cursor  cursor = db.rawQuery("select * from lfcy_user_inf where cUserCode = ?", name);
    		int nameColumnIndex = cursor.getColumnCount();
    		cursor.moveToFirst();
    		String YOYO_NAME = cursor.getString(1).toString();
    		String YOYO_CODE = cursor.getString(2).toString();
    		String YOYO_PASSWORD = cursor.getString(3).toString();
    		String YOYO_MANAGER = cursor.getString(4).toString();
    		String YOYO_LIMIT = cursor.getString(5).toString();
    		
    		String b=new String(YOYO_PASSWORD); 
    		
    		if( User_Password.equals(b) )
    		{	
//	    		Toast.makeText(Login.this, "查询"+name[0] +" == "+ nameColumnIndex +"  "+ YOYO_NAME+"  "+ YOYO_CODE+"  "+ 
//	    				  YOYO_PASSWORD+"  "+ YOYO_MANAGER+"  " + YOYO_LIMIT,
//					     Toast.LENGTH_SHORT).show();	
	    		Equal= true;
    		}
	    	else
	    	{
	    		Toast.makeText(Login.this," 密码错误！ 请重新输入 ",
	   				     Toast.LENGTH_SHORT).show();	   			
	    		Equal = false;
	    	}
    				
    	} 
		catch (Exception e) 
		{
			Toast.makeText(Login.this," 没有此用户  ",
				     Toast.LENGTH_SHORT).show();
			Equal =	false;
		}
		
		return Equal;

	}
	
	//对比数据
	
	
	
	private void key_things() {
		BTN_ENTER.setOnClickListener(new Button.OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{	
	    		if( BTN_USER_NAME.getText().toString().equals("0716") )
	    		{	
	    			finish();
					android.os.Process
					.killProcess(android.os.Process
							.myPid());
	    		}
		   		if( find_password() )
		   		{
			   	    Bundle bundle = new Bundle();
			   	    //保存输入的信息
			   	    bundle.putString("UserCode", BTN_USER_NAME.getText().toString());
			   	    bundle.putString("UserLimit","操作员");
		    		Intent intent_page_new = new Intent();

		    		if( SELL_MANAGE == true )
		    			intent_page_new.setClass(Login.this, Table2.class);
		    		else
		    			intent_page_new.setClass(Login.this, POS_System.class);

		    		intent_page_new.putExtras(bundle);		    			
		    		startActivity(intent_page_new);	
					overridePendingTransition(R.anim.zoomin, R.anim.zoomout);		   			
		   		}
				BTN_USER_PASSWORD.setText("");
		   	}
	    });	
		
		BTN_ENTER_CARD.setOnClickListener(new Button.OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{	
		   		find_password();
				BTN_USER_PASSWORD.setText("");
		   	}
	    });	
		
		BTN_QUIT.setOnClickListener(new Button.OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{	
//	    		showDialog(DIALOG_QUIT);
//		   		execShell("reboot");
		   		showRebootDialog();
//		   		android.os.Process.killProcess(android.os.Process.myPid());
		   	}
	    });	
		
		BTN_NUM_1.setOnClickListener(new Button.OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{	
		   		if ( NAME_PASSWORD)
		   		{
			   		num =  BTN_USER_NAME.getText().toString();
			   		BTN_USER_NAME.setText(num+"1");		   			
		   		}
		   		else
		   		{
			   		password =  BTN_USER_PASSWORD.getText().toString();
			   		BTN_USER_PASSWORD.setText(password+"1");			   			
		   		}	
		   	}
	    });	
		BTN_NUM_2.setOnClickListener(new Button.OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{
		   		if ( NAME_PASSWORD)
		   		{
			   		num =  BTN_USER_NAME.getText().toString();
			   		BTN_USER_NAME.setText(num+"2");		   			
		   		}
		   		else
		   		{
			   		password =  BTN_USER_PASSWORD.getText().toString();
			   		BTN_USER_PASSWORD.setText(password+"2");			   			
		   		}	
		   	}
	    });		
		BTN_NUM_3.setOnClickListener(new Button.OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{
		   		if ( NAME_PASSWORD)
		   		{
			   		num =  BTN_USER_NAME.getText().toString();
			   		BTN_USER_NAME.setText(num+"3");		   			
		   		}
		   		else
		   		{
			   		password =  BTN_USER_PASSWORD.getText().toString();
			   		BTN_USER_PASSWORD.setText(password+"3");			   			
		   		}	
		   	}
	    });			
		BTN_NUM_4.setOnClickListener(new Button.OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{
		   		if ( NAME_PASSWORD)
		   		{
			   		num =  BTN_USER_NAME.getText().toString();
			   		BTN_USER_NAME.setText(num+"4");		   			
		   		}
		   		else
		   		{
			   		password =  BTN_USER_PASSWORD.getText().toString();
			   		BTN_USER_PASSWORD.setText(password+"4");			   			
		   		}	
		   	}
	    });			
		BTN_NUM_5.setOnClickListener(new Button.OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{
		   		if ( NAME_PASSWORD)
		   		{
			   		num =  BTN_USER_NAME.getText().toString();
			   		BTN_USER_NAME.setText(num+"5");		   			
		   		}
		   		else
		   		{
			   		password =  BTN_USER_PASSWORD.getText().toString();
			   		BTN_USER_PASSWORD.setText(password+"5");			   			
		   		}	
		   	}
	    });			
		BTN_NUM_6.setOnClickListener(new Button.OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{
		   		if ( NAME_PASSWORD)
		   		{
			   		num =  BTN_USER_NAME.getText().toString();
			   		BTN_USER_NAME.setText(num+"6");		   			
		   		}
		   		else
		   		{
			   		password =  BTN_USER_PASSWORD.getText().toString();
			   		BTN_USER_PASSWORD.setText(password+"6");			   			
		   		}		
		   	}
	    });			
		
		BTN_NUM_7.setOnClickListener(new Button.OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{
		   		if ( NAME_PASSWORD)
		   		{
			   		num =  BTN_USER_NAME.getText().toString();
			   		BTN_USER_NAME.setText(num+"7");		   			
		   		}
		   		else
		   		{
			   		password =  BTN_USER_PASSWORD.getText().toString();
			   		BTN_USER_PASSWORD.setText(password+"7");			   			
		   		}	
		   	}
	    });	
		BTN_NUM_8.setOnClickListener(new Button.OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{
		   		if ( NAME_PASSWORD)
		   		{
			   		num =  BTN_USER_NAME.getText().toString();
			   		BTN_USER_NAME.setText(num+"8");		   			
		   		}
		   		else
		   		{
			   		password =  BTN_USER_PASSWORD.getText().toString();
			   		BTN_USER_PASSWORD.setText(password+"8");			   			
		   		}	
		   	}
	    });		
		BTN_NUM_9.setOnClickListener(new Button.OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{
		   		if ( NAME_PASSWORD)
		   		{
			   		num =  BTN_USER_NAME.getText().toString();
			   		BTN_USER_NAME.setText(num+"9");		   			
		   		}
		   		else
		   		{
			   		password =  BTN_USER_PASSWORD.getText().toString();
			   		BTN_USER_PASSWORD.setText(password+"9");			   			
		   		}	
		   	}
	    });
		BTN_NUM_0.setOnClickListener(new Button.OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{
		   		if ( NAME_PASSWORD)
		   		{
			   		num =  BTN_USER_NAME.getText().toString();
			   		BTN_USER_NAME.setText(num+"0");		   			
		   		}
		   		else
		   		{
			   		password =  BTN_USER_PASSWORD.getText().toString();
			   		BTN_USER_PASSWORD.setText(password+"0");			   			
		   		}	
		   	}
	    });	

/*
		BTN_NUM_DEL.setOnClickListener(new Button.OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{
		   		String str = null;

		   		try {
			   		if ( NAME_PASSWORD)
			   		{
				   		num =  BTN_USER_NAME.getText().toString();
			   			str=num.substring(0,num.length()-1);
				   		BTN_USER_NAME.setText(str);	   			
			   		}
			   		else
			   		{
				   		password =  BTN_USER_PASSWORD.getText().toString();
			   			str=password.substring(0,password.length()-1);
			   			BTN_USER_PASSWORD.setText(str);		   			
			   		}						
				} catch (Exception e) {
					// TODO: handle exception
				}
		   	}
	    });
*/		
		BTN_NUM_CLEAR.setOnClickListener(new Button.OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{
		   		if ( NAME_PASSWORD)
		   		{
			   		num =  BTN_USER_NAME.getText().toString();
			   		BTN_USER_NAME.setText("");		   			
		   		}
		   		else
		   		{
			   		password =  BTN_USER_PASSWORD.getText().toString();
			   		BTN_USER_PASSWORD.setText("");			   			
		   		}
		   	}
	    });
		
		BTN_QT_SELL.setOnClickListener(new Button.OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{
		   		if( SELL_MANAGE == false )
		   		{
			   		SELL_MANAGE = true;
			   		BTN_QT_SELL.setBackgroundResource(R.drawable.login_qt_on);
			   		BTN_HT_MANAGE.setBackgroundResource(R.drawable.login_ht_off);			   		
			   		AbsoluteLayout.LayoutParams	view_para	=	
			   			new	AbsoluteLayout.LayoutParams(110, 50, 460, 285);
			   		BTN_BACK.setLayoutParams(view_para);

					AnimationSet animationSet = new AnimationSet(true); 
					TranslateAnimation translateAnimation = new TranslateAnimation( 
							Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0f, 
							Animation.RELATIVE_TO_SELF, 1.0f, Animation.RELATIVE_TO_SELF, 0f); 
					translateAnimation.setDuration(200); 
					animationSet.addAnimation(translateAnimation); 
			   		BTN_BACK.startAnimation(animationSet);		   		
		   		}	
		   	}
	    });			
		BTN_HT_MANAGE.setOnClickListener(new Button.OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{
		   		if( SELL_MANAGE == true )
		   		{
			   		SELL_MANAGE = false;
			   		BTN_QT_SELL.setBackgroundResource(R.drawable.login_qt_off);
			   		BTN_HT_MANAGE.setBackgroundResource(R.drawable.login_ht_on);			   		
			   		AbsoluteLayout.LayoutParams	view_para	=	
			   			new	AbsoluteLayout.LayoutParams(110, 50, 460, 345);
			   		BTN_BACK.setLayoutParams(view_para);

					AnimationSet animationSet = new AnimationSet(true); 
					TranslateAnimation translateAnimation = new TranslateAnimation( 
							Animation.RELATIVE_TO_SELF, 0.0f, Animation.RELATIVE_TO_SELF, 0f, 
							Animation.RELATIVE_TO_SELF, -1.0f, Animation.RELATIVE_TO_SELF, 0.0f); 
					translateAnimation.setDuration(200); 
					animationSet.addAnimation(translateAnimation); 
			   		BTN_BACK.startAnimation(animationSet);

		   		}	
		   	}
	    });		
		
		
		BTN_USER_NAME.setOnClickListener(new Button.OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{
	   			NAME_PASSWORD = true;
		   		BTN_USER_NAME.setBackgroundResource(R.drawable.edit_button_on);
		   		BTN_USER_PASSWORD.setBackgroundResource(R.drawable.edit_button_off);			   		
		   		BTN_NAME_DEL.setVisibility(View.VISIBLE);
		   		BTN_PASSWORD_DEL.setVisibility(View.GONE);
		   	}
	    });	
		
		BTN_USER_PASSWORD.setOnClickListener(new Button.OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{
	   			NAME_PASSWORD = false;
		   		BTN_USER_NAME.setBackgroundResource(R.drawable.edit_button_off);
		   		BTN_USER_PASSWORD.setBackgroundResource(R.drawable.edit_button_on);			   		
		   		BTN_NAME_DEL.setVisibility(View.GONE);
		   		BTN_PASSWORD_DEL.setVisibility(View.VISIBLE);		   		
		   	}
	    });					

		BTN_NAME_DEL.setOnClickListener(new Button.OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{
		   		try {
			   		String str = null;
			   		num =  BTN_USER_NAME.getText().toString();
		   			str=num.substring(0,num.length()-1);
			   		BTN_USER_NAME.setText(str);						
				} catch (Exception e) {
					// TODO: handle exception
				}
   
		   	}
	    });			

		BTN_PASSWORD_DEL.setOnClickListener(new Button.OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{
		   		try {
			   		String str = null;
			   		num =  BTN_USER_PASSWORD.getText().toString();
		   			str=num.substring(0,num.length()-1);
		   			BTN_USER_PASSWORD.setText(str);	 					
				} catch (Exception e) {
					// TODO: handle exception
				}
		   	}
	    });	
	}

	public void execShell(String cmd){
    	try{  
            //权限设置
            Process p = Runtime.getRuntime().exec("su");  
            //获取输出流
            OutputStream outputStream = p.getOutputStream();
            DataOutputStream dataOutputStream=new DataOutputStream(outputStream);
            //将命令写入
            dataOutputStream.writeBytes(cmd);
            //提交命令
            dataOutputStream.flush();
            //关闭流操作
            dataOutputStream.close();
            outputStream.close();
       }  
       catch(Throwable t)  
       {  
             t.printStackTrace();  
       } 
    }
	
	private void find_view() {
		// TODO Auto-generated method stub
		BTN_ENTER = (Button) findViewById(R.id.button_enter_casio);
		BTN_ENTER_CARD = (Button) findViewById(R.id.btn_control_card);
		BTN_QUIT = (Button) findViewById(R.id.button_login_off);
		BTN_QT_SELL = (Button) findViewById(R.id.button_qt);
		BTN_HT_MANAGE = (Button) findViewById(R.id.button_ht);

		BTN_NUM_0= (Button) findViewById(R.id.btn_control_0);
		BTN_NUM_1= (Button) findViewById(R.id.btn_control_1);
		BTN_NUM_2= (Button) findViewById(R.id.btn_control_2);
		BTN_NUM_3= (Button) findViewById(R.id.btn_control_3);
		BTN_NUM_4= (Button) findViewById(R.id.btn_control_4);
		BTN_NUM_5= (Button) findViewById(R.id.btn_control_5);
		BTN_NUM_6= (Button) findViewById(R.id.btn_control_6);
		BTN_NUM_7= (Button) findViewById(R.id.btn_control_7);
		BTN_NUM_8= (Button) findViewById(R.id.btn_control_8);
		BTN_NUM_9= (Button) findViewById(R.id.btn_control_9);
		BTN_NUM_CLEAR= (Button) findViewById(R.id.btn_control_clear);
//		BTN_NUM_DEL= (Button) findViewById(R.id.btn_control_del);
		BTN_NAME_DEL= (Button) findViewById(R.id.edit_name_del);
		BTN_PASSWORD_DEL= (Button) findViewById(R.id.edit_password_del);
		BTN_BACK	=	(ImageView) findViewById(R.id.button_back_choose);
		BTN_USER_NAME		= (Button) findViewById(R.id.edit_btn_name);
		BTN_USER_PASSWORD	= (Button) findViewById(R.id.edit_btn_password);
	
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			showBackDialog();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}
	
	/** Give the tip when exit the application. */
	public void showBackDialog() {
		final AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Android收银终端 ")
				.setIcon(R.drawable.icon)
				.setMessage("是否退出?")
				.setPositiveButton("退出",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
//								System.exit(0);
								android.os.Process
										.killProcess(android.os.Process
												.myPid());
								dialog.dismiss();
							}
						})
				.setNegativeButton("返回",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();
							}
						});
		
		AlertDialog ad = builder.create();
		ad.show();
	}

	
	/** Give the tip when exit the application. */
	public void showRebootDialog() {
		final AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Android收银终端 ")
				.setIcon(R.drawable.icon)
				.setMessage("是否重启?")
				.setPositiveButton("重启",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
//								System.exit(0);
								execShell("reboot");
								dialog.dismiss();
							}
						})
				.setNegativeButton("取消",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.dismiss();
							}
						});
		
		AlertDialog ad = builder.create();
		ad.show();
	}
	
    /****************    以下是控制网络的线程  ******************************/
	MyThread read_tcp = new MyThread();		//接收PC端数据的线程

	//接收PC端数据的线程
	class MyThread extends Thread 
	{  

		public void run() 
		{
			try {
				control_wifi();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}	
	}
	
	private void control_wifi() throws IOException
	{
		System.out.println("net is wait");
		boolean	net_code = true;	//判断这一条数据是不是命令字
		int	net_code_switch = 0;
		// 创建一个ServerSocket，用于监听客户端Socket的连接请求
		ServerSocket ss = new ServerSocket(30000);
		// 采用循环不断接受来自客户端的请求
		while (true)
		{
	        Log.i("info", "[LF Android Test Info]   net is ready");  

			// 每当接受到客户端Socket的请求，服务器端也对应产生一个Socket
			Socket s = ss.accept();
	        Log.i("info", "[LF Android Test Info]   net is accept");  
			
 			// 将Socket对应的输出流包装成PrintStream
			PrintStream ps = new PrintStream(s.getOutputStream());
			
			//接收
			BufferedReader br = new BufferedReader(
					new InputStreamReader(s.getInputStream()));
					// 进行普通IO操作
			String line = br.readLine();
			//line是获取到的有效数据，它可能是   "命令字" 也可能是 "数据"  
			//由命令字决定接下来的数据是发打印还是发数据库还是控制其他什么部分
	        Log.i("info", "[LF Android Test Info]   line = " + line);  

			if(net_code == true)
			{
				net_code_switch	= 0;

				if (line.equals("pppp")) 	//如果收到的字符串是pppp 
				{
					net_code_switch = 1;	//命令方式是发厨房打印
				} 
				if (line.equals("qqqq")) 	//如果收到的字符串是qqqq 
				{
					net_code_switch = 2;	//命令方式是发数据库
				} 
				if (line.equals("qqqq_updata_tablestate")) 	
				{
					net_code_switch = 3;	//命令方式是发数据库更新桌台状态
				} 
				if (line.equals("qqqq_insert_opentable")) 
				{
					net_code_switch = 4;	//命令方式是发数据库增加开台信息及开台单号
				} 				
				if (line.equals("qqqq_insert_sellinf")) 
				{
					net_code_switch = 5;	//命令方式是发数据库增加开台信息及开台单号
				} 
				if (line.equals("qqq_qingtai_lfcy_base_tableinf")) 
				{
					net_code_switch = 6;	//命令方式是发数据库实现清台同步
				} 
				if (line.equals("qqqq_clude_all")) 
				{
					net_code_switch = 7;	//命令方式是一开始同步菜品信息
				} 
				if (line.equals("qqqq_clude_table")) 
				{
					net_code_switch = 8;	//命令方式是一开始同步桌台信息
				} 
				if (line.equals("qqqq_get_table_opennum")) 
				{
					net_code_switch = 9;	//命令方式是获取开台单号
				} 
				if (line.equals("qqqq_yidian_cai")) 
				{
					net_code_switch = 10;	//命令方式是获取已点菜
				} 
				if (line.equals("qqqq_newdiain_cai")) 
				{
					net_code_switch = 11;	//命令方式是获取新增菜
				}
				if (line.equals("qqqq_clear_newsellinf")) 
				{
					net_code_switch = 12;	//命令方式是发数据库实现清台同步
				}
				if (line.equals("qqqq_update_lfcy_base_sellinf_new")) 
				{
					net_code_switch = 13;	//命令方式是发数据库实现清台同步
				}
				if (line.equals("qqqq_clude_bigclass")) 
				{
					net_code_switch = 14;	//命令方式是获取大类
				}
				if (line.equals("qqqq_clude_smallclass")) 
				{
					net_code_switch = 15;	//命令方式是获取小类
				}
				if (line.equals("qqqq_clude_tabletype")) 
				{
					net_code_switch = 16;	//命令方式是获取小类
				}
				net_code = false;
			}	
			else
			{
				switch (net_code_switch) {
				case 1:
			   	    int	   TTY_BPS = 9600;			//串口的初始信息！只在安装后第一次有用！以后会从xml中读出配置信息
			   		String TTY_DEV = "/dev/ttymxc2";
			   		String	SPF_Prt1_bt	=	"SPF_Prt1_bt";
			   		String	SPF_Prt2_bt	=	"SPF_Prt2_bt";
			   		String	SPF_Prt3_bt	=	"SPF_Prt3_bt";			   		
			   		String	SPF_Com_1	=	"SPF_Com_1";
					String	SPF_Com_2	=	"SPF_Com_2";
					String	SPF_Com_3	=	"SPF_Com_3";
			   		String[] btl_String = getResources().getStringArray(R.array.botelv);

					SharedPreferences settings = getSharedPreferences("Prt_Setup_SharedPreferences", 0);		
					String COM_1 = settings.getString(SPF_Com_1, null);
					String COM_2 = settings.getString(SPF_Com_2, null);
					String COM_3 = settings.getString(SPF_Com_3, null);
			        Log.i("info", "COM = "+ COM_1 + COM_2 + COM_3);  

					if (COM_1.trim().equals("ChuDa") ||COM_1.trim().equals("BingYong")) {
						TTY_DEV = "/dev/ttymxc4";
						TTY_BPS = settings.getInt(SPF_Prt1_bt, 0);
					    Integer intObj = new Integer(btl_String[TTY_BPS]);
					    TTY_BPS = intObj.intValue();	
					} else {
						if (COM_2.trim().equals("ChuDa") ||COM_2.trim().equals("BingYong") ) {
							TTY_DEV = "/dev/ttymxc3";
							TTY_BPS = settings.getInt(SPF_Prt2_bt, 0);
						    Integer intObj = new Integer(btl_String[TTY_BPS]);
						    TTY_BPS = intObj.intValue();
						} else {
							if (COM_3.trim().equals("ChuDa")|| COM_3.trim().equals("BingYong")) {
								TTY_DEV = "/dev/ttymxc2";
								TTY_BPS = settings.getInt(SPF_Prt3_bt, 0);
							    Integer intObj = new Integer(btl_String[TTY_BPS]);
							    TTY_BPS = intObj.intValue();
							} else {
								
							}
						}
					}
			        Log.i("info", "TTY_DEV = "+ TTY_DEV);  

					try {
						mSerialPort = new SerialPort(new File(TTY_DEV), TTY_BPS, 0);
					} catch (SecurityException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}					
					mOutputStream = mSerialPort.getOutputStream();
					
					byte[] cancel_to_normal = {0x0a, 0x1b, 0x21, 0x00};//取消倍高倍宽
					print_String(cancel_to_normal,line);	//交给打印机打印	
					
					break;
				case 2:
					try {
			    		Cursor  cursor = db.rawQuery("select iTableState from lfcy_base_tableinf ", null);
			    		String  fuffer = "0" ;
			    		while (cursor.moveToNext()) {
				    		String state = cursor.getString(cursor.getColumnIndex("iTableState"))+";";			    			
//							System.out.println("qqqq successful "+ "   "+state);							
							fuffer = fuffer + state;
			    		};
//						System.out.println("qqqq end =  "+ "   "+fuffer);
						ps = new PrintStream(s.getOutputStream());
						// 进行普通IO操作
						ps.println(fuffer);
					} catch (Exception e) {
						// TODO: handle exception
						System.out.println("qqqq failed");
					}
					break;
				case 3:		//更新桌台信息
					try {
						String[] res = line.split(";");
				   		ContentValues cv = new ContentValues();
					   	//存储修改的数据
					   	cv.put("iTableState" ,2);
					   	cv.put("iTable_Person",res[0]);
					   	cv.put("iTabletime",res[1]);
					   	String[] contion = {res[2]}; 
						//更新数据
						db.update("lfcy_base_tableinf",cv,"iTableNumber = ? ",contion);
					} catch (Exception e) {
						// TODO: handle exception
						System.out.println("lfcy_base_tableinf failed");
					}
					break;
				case 4:		//更新桌台信息
			   		try {
						String[] res = line.split(";");
					   	//更新数据
					   	db.execSQL("insert into lfcy_base_opentableinf values(?,?)", 
								new String[]{
					   			res[0] , res[1]});
					} catch (Exception e) {
						// TODO: handle exception
						System.out.println("lfcy_base_opentableinf failed");
					}
					break;
				case 5:		//更新桌台信息
			   		try {
						String[] res = line.split(";");
						
				    	int mYear,mMonth,mDay,mHour,mMinute,mSecond;
				    	//获取桌台号和即时时间    
				   		final Calendar c = 	Calendar.getInstance();
				        mYear	= c.get(Calendar.YEAR); 	//获取当前年份
				        mMonth 	= c.get(Calendar.MONTH)+ 1;	//获取当前月份
				        mDay 	= c.get(Calendar.DAY_OF_MONTH);//获取当前月份的日期号码
				        mHour 	= c.get(Calendar.HOUR_OF_DAY);//获取当前的小时数
				        mMinute = c.get(Calendar.MINUTE);	//获取当前的分钟数		   		
				        mSecond = c.get(Calendar.SECOND);	//获取当前的秒钟数		   		

				   		String mmHour,mmMinute,mmSecond;

				   		if(mHour < 10)
				   			mmHour = "0"+mHour;
				   		else
				   			mmHour = ""+mHour;

				   		if(mMinute < 10)
				   			mmMinute = "0"+mMinute;
				   		else
				   			mmMinute = ""+mMinute;

				   		if(mSecond < 10)
				   			mmSecond = "0"+mSecond;
				   		else
				   			mmSecond = ""+mSecond;

				   		String	system_date	= mYear+"-"+mMonth+"-"+	mDay;
				   		String	system_time	= mmHour+":"+mmMinute+":"+mmSecond;
				   		String  str = system_date + " "+system_time;	
					   	//更新数据
						db.execSQL("insert into lfcy_base_sellinf values(null,?,?,?,?,?,?,?,?,?)", 								
							new String[]{
					   			res[0] , res[1] ,res[2],res[3],res[4],res[5] ,res[6],res[7],str});
						System.out.println("res[0] = " + res[0]);
						System.out.println("res[1] = " + res[1]);
						System.out.println("res[2] = " + res[2]);
						System.out.println("res[3] = " + res[3]);
						System.out.println("res[4] = " + res[4]);
						System.out.println("res[5] = " + res[5]);
						System.out.println("res[6] = " + res[6]);
						System.out.println("str = " + str);
						
					} catch (Exception e) {
						// TODO: handle exception
						System.out.println("qqqq_insert_sellinf  failed");
					}
					break;					
				case 6:		//实现清台同步
			   		try {
				   		//消台
				   		ContentValues cv = new ContentValues();
					   	//存储修改的数据
					   	cv.put("iTableState" ,1);
					   	cv.put("iTable_Person","");
					   	cv.put("iTabletime","");
					   	String[] contion = {line}; 
				   		try {
				   			//更新数据
						   	db.update("lfcy_base_tableinf",cv,"iTableNumber = ? ",contion);
						} catch (Exception e) {
							// TODO: handle exception
						}
					} catch (Exception e) {
						// TODO: handle exception
						System.out.println("qqq_qingtai_lfcy_base_tableinf  failed");
					}
					break;	
				case 7:
					try {
			    		Cursor  cursor = db.rawQuery("select * from lfcy_base_dishinf ", null);
			    		String  fuffer = "0" ;
			    		while (cursor.moveToNext()) {
				    		String cDishName 	= cursor.getString(cursor.getColumnIndex("cDishName"))+";";			    			
				    		String cDishName2	= cursor.getString(cursor.getColumnIndex("cDishName2"))+";";		 
				    		String cDishCode 	= cursor.getString(cursor.getColumnIndex("cDishCode"))+";";
				    		String cDishPinYin 	= cursor.getString(cursor.getColumnIndex("cDishPinYin"))+";";
				    		String cDishHelpCode= cursor.getString(cursor.getColumnIndex("cDishHelpCode"))+";";
				    		String cDishClass1 	= cursor.getString(cursor.getColumnIndex("cDishClass1"))+";";
				    		String cDishClass2 	= cursor.getString(cursor.getColumnIndex("cDishClass2"))+";";
				    		String cDishUnitName= cursor.getString(cursor.getColumnIndex("cDishUnitName"))+";";
				    		String cDishUnitCode= cursor.getString(cursor.getColumnIndex("cDishUnitCode"))+";";
				    		String iDishStyle 	= cursor.getString(cursor.getColumnIndex("iDishStyle"))+";";
				    		String iDishDian 	= cursor.getString(cursor.getColumnIndex("iDishDian"))+";";
				    		String fDishPrice 	= cursor.getString(cursor.getColumnIndex("fDishPrice"))+";";

				    		String state = cDishName +cDishName2+cDishCode+cDishPinYin+cDishHelpCode
				    			+cDishClass1+cDishClass2+cDishUnitName+cDishUnitCode+iDishStyle+iDishDian+fDishPrice;
							fuffer = fuffer +","+ state;

				    		System.out.println("qqqq clude_all "+ "   "+state);			
			    		};
//						System.out.println("qqqq end =  "+ "   "+fuffer);
						ps = new PrintStream(s.getOutputStream());
						// 进行普通IO操作
						ps.println(fuffer);
					} catch (Exception e) {
						// TODO: handle exception
						System.out.println("qqqq failed");
					}
					break;					
				case 8:
					try {
			    		System.out.println("wl  select * from  lfcy_base_tableinf ");									
			    		Cursor  cursor = db.rawQuery("select * from lfcy_base_tableinf ", null);
			    		String  fuffer = "0" ;
			    		while (cursor.moveToNext()) {				    		
				    		String	iTableNumber	= cursor.getString(cursor.getColumnIndex("iTableNumber"))+";";	
				    		String	iTableClass 	= cursor.getString(cursor.getColumnIndex("iTableClass"))+";";	
				    		String	iTableClass2 	= cursor.getString(cursor.getColumnIndex("iTableClass2"))+";";
				    		String	iTableState 	= cursor.getString(cursor.getColumnIndex("iTableState"))+";";
				    		String	iTabletime 		= cursor.getString(cursor.getColumnIndex("iTabletime"))+";";
				    		if(iTabletime.equals(";") || iTabletime == null){//会抛出异常
				    			iTabletime = "null"+";";
					    		System.out.println("iTabletime = null");			
				    		}
				    		String	iTablePerson 	= cursor.getString(cursor.getColumnIndex("iTablePerson"))+";";
				    		String	iTable_Person	= cursor.getString(cursor.getColumnIndex("iTable_Person"))+";";
				    		if(iTable_Person.equals(";") || iTable_Person == null){//会抛出异常
				    			iTable_Person = "null"+";";
					    		System.out.println("iTable_Person = null");			
				    		}							
				    		String state = iTableNumber +iTableClass+iTableClass2+iTableState+iTabletime+iTablePerson+iTable_Person;
							fuffer = fuffer +","+ state;

				    		System.out.println("qqqq clude_all_table "+ "   "+state);			
			    		};

						ps = new PrintStream(s.getOutputStream());
						// 进行普通IO操作
						ps.println(fuffer);
					} catch (Exception e) {
						// TODO: handle exception
						System.out.println("qqqq clude_all_table failed");
					}
					break;	
				case 9:
					System.out.println("table_num = "+ line);
			   		String openNum = get_table_sellnum(line);	
					System.out.println("table_num = "+ openNum);
					try {
						ps = new PrintStream(s.getOutputStream());
						// 进行普通IO操作
						ps.println(openNum);
						System.out.println(openNum);
					} catch (Exception e) {
						// TODO: handle exception
						System.out.println("qqqq_get_table_opennum failed");
					}
					break;	
				case 10:
					//获取开台单号
					System.out.println("Sellnum = "+ line);
					String[] sell_number = {line};

					//根据开台单号，获取该单号的已点菜
					try {
						Cursor  cursor = db.rawQuery("select * from lfcy_base_sellinf where cSellNo= ?", sell_number);
			    		String  fuffer = "0" ;
			    		while (cursor.moveToNext()) {				    		
				    		String	iTableNumber	= cursor.getString(cursor.getColumnIndex("iTableNumber"))+";";	
				    		String	cSellNo 		= cursor.getString(cursor.getColumnIndex("cSellNo"))+";";	
				    		String	cDishName 		= cursor.getString(cursor.getColumnIndex("cDishName"))+";";
				    		String	cDishCode 		= cursor.getString(cursor.getColumnIndex("cDishCode"))+";";
				    		String	fDishPrice 		= cursor.getString(cursor.getColumnIndex("fDishPrice"))+";";
				    		String	cDishQty 		= cursor.getString(cursor.getColumnIndex("cDishQty"))+";";
				    		String	cDishUnitName 		= cursor.getString(cursor.getColumnIndex("cDishUnitName"))+";";
				    		String	cDishUnitCode 		= cursor.getString(cursor.getColumnIndex("cDishUnitCode"))+";";
/*
 							//处理出现空字符串时的方法
				    		if(iTabletime.equals(";") || iTabletime == null){//会抛出异常
				    			iTabletime = "null"+";";
					    		System.out.println("iTabletime = null");			
				    		}
*/	
							//把已点菜的相关信息用“;”和“,”组合起来
				    		String state = iTableNumber +cSellNo+cDishName+cDishCode+fDishPrice+
				    					cDishQty+cDishUnitName+cDishUnitCode;
							fuffer = fuffer +","+ state;

				    		System.out.println("qqqq qqqq_yidian_cai "+ "   "+state);			
			    		};

						ps = new PrintStream(s.getOutputStream());
						// 进行普通IO操作
						//发送给手机客户端
						ps.println(fuffer);
					} catch (Exception e) {
						// TODO: handle exception
						System.out.println("qqqq qqqq_yidian_cai failed");
					}
					break;
				case 11:
					//获取开台单号
					System.out.println("Sellnum = "+ line);
					String[] sell_numberr = {line};

					//根据开台单号，获取该单号的已点菜
					try {
						Cursor  cursor = db.rawQuery("select * from lfcy_base_sellinf_new where cSellNo= ?", sell_numberr);
			    		String  fuffer = "0" ;
			    		while (cursor.moveToNext()) {				    		
				    		String	iTableNumber	= cursor.getString(cursor.getColumnIndex("iTableNumber"))+";";	
				    		String	cSellNo 		= cursor.getString(cursor.getColumnIndex("cSellNo"))+";";	
				    		String	cDishName 		= cursor.getString(cursor.getColumnIndex("cDishName"))+";";
				    		String	cDishCode 		= cursor.getString(cursor.getColumnIndex("cDishCode"))+";";
				    		String	fDishPrice 		= cursor.getString(cursor.getColumnIndex("fDishPrice"))+";";
				    		String	cDishQty 		= cursor.getString(cursor.getColumnIndex("cDishQty"))+";";
				    		String	cDishUnitName 		= cursor.getString(cursor.getColumnIndex("cDishUnitName"))+";";
				    		String	cDishUnitCode 		= cursor.getString(cursor.getColumnIndex("cDishUnitCode"))+";";
/*
 							//处理出现空字符串时的方法
				    		if(iTabletime.equals(";") || iTabletime == null){//会抛出异常
				    			iTabletime = "null"+";";
					    		System.out.println("iTabletime = null");			
				    		}
*/	
							//把已点菜的相关信息用“;”和“,”组合起来
				    		String state = iTableNumber +cSellNo+cDishName+cDishCode+fDishPrice+cDishQty+cDishUnitName+cDishUnitCode;
							fuffer = fuffer +","+ state;

				    		System.out.println("qqqq qqqq_newdian_cai "+ "   "+state);			
			    		};

						ps = new PrintStream(s.getOutputStream());
						// 进行普通IO操作
						//发送给手机客户端
						ps.println(fuffer);
					} catch (Exception e) {
						// TODO: handle exception
						System.out.println("qqqq qqqq_newdian_cai failed");
					}
					break;
				case 12:
					System.out.println("-----table_num = "+ line);
			   		//清除LIST_NEW并刷新LIST_DIANCAI
			   		try {
			   			db.delete("lfcy_base_sellinf_new", " cSellNo =?", new String[]{line});
						System.out.println("lfcy_base_sellinf_new success");
		   			} catch (Exception e) {
						System.out.println("!!!!!!!!lfcy_base_sellinf_new success  failed");	
		   			}	
					break;						
				case 13:
					//更新新增菜品数据
					String[] clomn = line.split(",");
					System.out.println(" "+clomn.length);

					for(int i = 0;i<clomn.length -1;i++)
					{	
						System.out.println(" "+clomn[i+1]);
						String   my_clomn = clomn[i+1];
						String[] res = my_clomn.split(";");
		    			
						String  iTableNumber= res[0];//桌台号
						String  cSellNo		= res[1];//销售单号（利用开台时间）
						String  cDishName 	= res[2];//销售菜品名称
						String  cDishCode 	= res[3];//销售菜品编码
						String  fDishPrice 	= res[4];//销售菜品单价
						String  cDishQty 	= res[5];//菜品销售数量

				
						insert_SellDishData_new(db, 
								iTableNumber,cSellNo,cDishName,	cDishCode,fDishPrice,cDishQty);
					}
					break;	
				case 14:
					try {
			    		System.out.println("wl  select * from  lfcy_base_bigsort ");									
			    		Cursor  cursor = db.rawQuery("select * from lfcy_base_bigsort ", null);
			    		String  fuffer = "0" ;
			    		while (cursor.moveToNext()) {				    		
				    		String	cName	= cursor.getString(cursor.getColumnIndex("cName"))+";";	
				    		String	cCode 	= cursor.getString(cursor.getColumnIndex("cCode"))+";";	
				    		String	cMemo 	= cursor.getString(cursor.getColumnIndex("cMemo"))+";";
				    		if(cMemo.equals(";") || cMemo == null){//会抛出异常
				    			cMemo = "null"+";";
					    		System.out.println("cMemo = null");			
				    		}							
				    		String state = cName +cCode+cMemo;
							fuffer = fuffer +","+ state;

				    		System.out.println("qqqq lfcy_base_bigsort "+ "   "+state);			
			    		};

						ps = new PrintStream(s.getOutputStream());
						// 进行普通IO操作
						ps.println(fuffer);
					} catch (Exception e) {
						// TODO: handle exception
						System.out.println("qqqq lfcy_base_bigsort failed");
					}
					break;	
				case 15:
					try {
			    		System.out.println("wl  select * from  lfcy_base_smallsort ");									
			    		Cursor  cursor = db.rawQuery("select * from lfcy_base_smallsort ", null);
			    		String  fuffer = "0" ;
			    		while (cursor.moveToNext()) {				    		
				    		String	cName	= cursor.getString(cursor.getColumnIndex("cName"))+";";	
				    		String	cCode 	= cursor.getString(cursor.getColumnIndex("cCode"))+";";	
				    		String	cMemo 	= cursor.getString(cursor.getColumnIndex("cMemo"))+";";
				    		if(cMemo.equals(";") || cMemo == null){//会抛出异常
				    			cMemo = "null"+";";
					    		System.out.println("cMemo = null");			
				    		}							
				    		String state = cName +cCode+cMemo;
							fuffer = fuffer +","+ state;

				    		System.out.println("qqqq lfcy_base_bigsort "+ "   "+state);			
			    		};

						ps = new PrintStream(s.getOutputStream());
						// 进行普通IO操作
						ps.println(fuffer);
					} catch (Exception e) {
						// TODO: handle exception
						System.out.println("qqqq lfcy_base_bigsort failed");
					}
					break;	
				case 16:
					try {
			    		System.out.println("wl  select * from  lfcy_base_tabletype ");									
			    		Cursor  cursor = db.rawQuery("select * from lfcy_base_tabletype ", null);
			    		String  fuffer = "0" ;
			    		while (cursor.moveToNext()) {				    		
				    		String	cName	= cursor.getString(cursor.getColumnIndex("cName"))+";";	
				    		String	cCode 	= cursor.getString(cursor.getColumnIndex("cCode"))+";";	
				    		String	cMemo 	= cursor.getString(cursor.getColumnIndex("cMemo"))+";";
				    		if(cMemo.equals(";") || cMemo == null){//会抛出异常
				    			cMemo = "null"+";";
					    		System.out.println("cMemo = null");			
				    		}							
				    		String state = cName +cCode+cMemo;
							fuffer = fuffer +","+ state;

				    		System.out.println("qqqq lfcy_base_tabletype "+ "   "+state);			
			    		};

						ps = new PrintStream(s.getOutputStream());
						// 进行普通IO操作
						ps.println(fuffer);
					} catch (Exception e) {
						// TODO: handle exception
						System.out.println("qqqq lfcy_base_bigsort failed");
					}
					break;						
				default:
					break;
				}
				
				net_code = true;
			}
			
			
			// 关闭输出流，关闭Socket
			br.close();
			ps.close();
			s.close();
		}
	}
    /****************    以上是控制网络的线程  ******************************/

    /****************    以下是串口打印的方法  ******************************/
	//我的打印机打印字符串的方法！！第一个参数是命令字！倍高倍宽之类！第二个参数是要打印的字符串！
	protected void print_String(byte[] prt_code_buffer, String in_String) {
		// TODO Auto-generated method stub
		int i;
		CharSequence t =  (CharSequence)in_String;
		char[] text = new char[t.length()];	//声明一个和所输入字符串同样长度的字符数组
		for (i=0; i<t.length(); i++) {
			text[i] = t.charAt(i);		//把CharSequence中的charAt传入刚声明的字符数组中
		}
		try {
			byte[] buffer = prt_code_buffer;//倍高倍宽;
			mOutputStream.write(buffer);
			mOutputStream.write(new String(text).getBytes("gb2312"));	//把字符数组变成byte型发送
		} catch (IOException e) {
			e.printStackTrace();
		}		
	}
    /****************    以上是串口打印的方法  ******************************/

    private	String get_table_sellnum(String table_num)
    {
    	String table_sellnum = null;
    	String[]	Stable_num = {table_num};
    	try {
    		Cursor  cursor = db.rawQuery("select * from lfcy_base_opentableinf where iTableNumber = ?", Stable_num);
    		cursor.moveToLast();
    		table_sellnum = cursor.getString(1).toString();
		} catch (Exception e) {
			// TODO: handle exception
		}
		return table_sellnum;
    }
  
	protected void insert_SellDishData_new(SQLiteDatabase db, String table_number,
			String sell_number, String cai_name, String cai_code,
			String cai_price, String cai_number) {
		// TODO Auto-generated method stub
		db.execSQL("insert into lfcy_base_sellinf_new values(null,?,?,?,?,?,?)", 
				new String[]{
					table_number ,sell_number ,	cai_name ,cai_code ,
					cai_price , cai_number  }
				);
	}
	
	
	/***************/
    /****************    以下是控制网络的线程  ******************************/
	TCP_Thread tcp_thread = new TCP_Thread();		//接收PC端数据的线程
	Handler handler;
	public static ArrayList<Socket> socketList = new ArrayList<Socket>();

	//接收PC端数据的线程
	class TCP_Thread extends Thread 
	{  

		public void run() 
		{
			try {
				ServerSocket ss = new ServerSocket(30002);
				while(true)
				{
					Socket s = ss.accept();
					socketList.add(s);
					new Thread(new ServerThread(s)).start();
				}			
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}	
	}
	
	public class ServerThread implements Runnable {

		Socket s = null;
		BufferedReader br = null;
		
		public ServerThread(Socket s) throws  IOException {
			// TODO Auto-generated constructor stub
			this.s = s;
			br = new BufferedReader(new InputStreamReader(s.getInputStream(),"utf-8"));
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				String content = null;				
				while( (content = readFromClient()) != null )
				{
					String[] clomn = content.split("@");
					Log.i("info", "clomn 0 = "+ clomn[0]);
					Log.i("info", "clomn 1 = "+ clomn[1]);
					if (clomn[0].equals("ppp")) {
						String   my_clomn = clomn[1];
						String[] res = my_clomn.split(";");
						Log.i("info", "res 0 = "+ res[0]);
						Log.i("info", "res 1 = "+ res[1]);
						Log.i("info", "res 2 = "+ res[2]);
						Log.i("info", "res 3 = "+ res[3]);
						Log.i("info", "res 4 = "+ res[4]);							

						OutputStream os = s.getOutputStream();
						os.write(("res 0 = "+ res[0] + "\n").getBytes("utf-8") );
						os.write(("res 1 = "+ res[1] + "\n").getBytes("utf-8") );
						os.write(("res 2 = "+ res[2] + "\n").getBytes("utf-8") );
						os.write(("res 3 = "+ res[3] + "\n").getBytes("utf-8") );
						os.write(("res 4 = "+ res[4] + "\n").getBytes("utf-8") );
					}	
					
					if (clomn[0].equals("pppp")) 	//如果收到的字符串是pppp 
					{
						//命令方式是发厨房打印
						String   my_clomn = clomn[1];
//						String[] res = my_clomn.split(";");
//						OutputStream os = s.getOutputStream();
//						os.write(("res 0 = "+ res[0] + "\n").getBytes("utf-8") );
//						os.write(("pppp " + "\n").getBytes("utf-8") );
						
				   	    int	   TTY_BPS = 9600;			//串口的初始信息！只在安装后第一次有用！以后会从xml中读出配置信息
				   		String TTY_DEV = "/dev/ttymxc2";
				   		String	SPF_Prt1_bt	=	"SPF_Prt1_bt";
				   		String	SPF_Prt2_bt	=	"SPF_Prt2_bt";
				   		String	SPF_Prt3_bt	=	"SPF_Prt3_bt";			   		
				   		String	SPF_Com_1	=	"SPF_Com_1";
						String	SPF_Com_2	=	"SPF_Com_2";
						String	SPF_Com_3	=	"SPF_Com_3";
				   		String[] btl_String = getResources().getStringArray(R.array.botelv);

						SharedPreferences settings = getSharedPreferences("Prt_Setup_SharedPreferences", 0);		
						String COM_1 = settings.getString(SPF_Com_1, null);
						String COM_2 = settings.getString(SPF_Com_2, null);
						String COM_3 = settings.getString(SPF_Com_3, null);
				        Log.i("info", "COM = "+ COM_1 + COM_2 + COM_3);  

						if (COM_1.trim().equals("ChuDa") ||COM_1.trim().equals("BingYong")) {
							TTY_DEV = "/dev/ttymxc4";
							TTY_BPS = settings.getInt(SPF_Prt1_bt, 0);
						    Integer intObj = new Integer(btl_String[TTY_BPS]);
						    TTY_BPS = intObj.intValue();	
						} else {
							if (COM_2.trim().equals("ChuDa") ||COM_2.trim().equals("BingYong") ) {
								TTY_DEV = "/dev/ttymxc3";
								TTY_BPS = settings.getInt(SPF_Prt2_bt, 0);
							    Integer intObj = new Integer(btl_String[TTY_BPS]);
							    TTY_BPS = intObj.intValue();
							} else {
								if (COM_3.trim().equals("ChuDa")|| COM_3.trim().equals("BingYong")) {
									TTY_DEV = "/dev/ttymxc2";
									TTY_BPS = settings.getInt(SPF_Prt3_bt, 0);
								    Integer intObj = new Integer(btl_String[TTY_BPS]);
								    TTY_BPS = intObj.intValue();
								} else {
									
								}
							}
						}
				        Log.i("info", "TTY_DEV = "+ TTY_DEV);  

						try {
							mSerialPort = new SerialPort(new File(TTY_DEV), TTY_BPS, 0);
						} catch (SecurityException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}					
						mOutputStream = mSerialPort.getOutputStream();
						
						byte[] cancel_to_normal = {0x0a, 0x1b, 0x21, 0x00};//取消倍高倍宽
						print_String(cancel_to_normal,my_clomn);	//交给打印机打印	
//						print_String(cancel_to_normal,null);	//交给打印机打印	
					} 
					if (clomn[0].equals("qqqq")) 	//如果收到的字符串是qqqq 
					{
						//命令方式是发数据库
						try {
				    		Cursor  cursor = db.rawQuery("select iTableState from lfcy_base_tableinf ", null);
				    		String  fuffer = "0" ;
				    		while (cursor.moveToNext()) {
					    		String state = cursor.getString(cursor.getColumnIndex("iTableState"))+";";			    			
								fuffer = fuffer + state;
				    		};
							
							OutputStream os = s.getOutputStream();
							os.write(( fuffer + "\n").getBytes("utf-8") );
						} catch (Exception e) {
							// TODO: handle exception
					        Log.i("info", "qqqq failed" );  
						}
					} 
					if (clomn[0].equals("qqqq_updata_tablestate")) 	
					{
						//命令方式是发数据库更新桌台状态
						try {
							String   my_clomn = clomn[1];
							String[] res = my_clomn.split(";");
					   		ContentValues cv = new ContentValues();
						   	//存储修改的数据
						   	cv.put("iTableState" ,2);
						   	cv.put("iTable_Person",res[0]);
						   	cv.put("iTabletime",res[1]);
						   	String[] contion = {res[2]}; 
							//更新数据
							db.update("lfcy_base_tableinf",cv,"iTableNumber = ? ",contion);
						} catch (Exception e) {
							// TODO: handle exception
							System.out.println("lfcy_base_tableinf failed");
						}
					} 
					if (clomn[0].equals("qqqq_insert_opentable")) 
					{
						//命令方式是发数据库增加开台信息及开台单号
						String   my_clomn = clomn[1];
				   		try {
							String[] res = my_clomn.split(";");
						   	//更新数据
						   	db.execSQL("insert into lfcy_base_opentableinf values(?,?)", 
									new String[]{
						   			res[0] , res[1]});
						} catch (Exception e) {
							// TODO: handle exception
							Log.i("info","lfcy_base_opentableinf failed");
						}
					} 				
					if (clomn[0].equals("qqqq_insert_sellinf")) 
					{
						//命令方式是发数据库增加开台信息及开台单号
					} 
					if (clomn[0].equals("qqq_qingtai_lfcy_base_tableinf")) 
					{
						//命令方式是发数据库实现清台同步
				   		try {
					   		//消台
					   		ContentValues cv = new ContentValues();
						   	//存储修改的数据
						   	cv.put("iTableState" ,1);
						   	cv.put("iTable_Person","");
						   	cv.put("iTabletime","");
						   	String[] contion = {clomn[1]}; 
					   		try {
					   			//更新数据
							   	db.update("lfcy_base_tableinf",cv,"iTableNumber = ? ",contion);
							} catch (Exception e) {
								// TODO: handle exception
							}
						} catch (Exception e) {
							// TODO: handle exception
							Log.i("info","qqq_qingtai_lfcy_base_tableinf  failed");
						}
					} 
					if (clomn[0].equals("qqqq_clude_all")) 
					{
						//命令方式是一开始同步菜品信息
						try {
				    		Cursor  cursor = db.rawQuery("select * from lfcy_base_dishinf ", null);
				    		String  fuffer = "0" ;
				    		while (cursor.moveToNext()) {
					    		String cDishName 	= cursor.getString(cursor.getColumnIndex("cDishName"))+";";			    			
					    		String cDishName2	= cursor.getString(cursor.getColumnIndex("cDishName2"))+";";		 
					    		String cDishCode 	= cursor.getString(cursor.getColumnIndex("cDishCode"))+";";
					    		String cDishPinYin 	= cursor.getString(cursor.getColumnIndex("cDishPinYin"))+";";
					    		String cDishHelpCode= cursor.getString(cursor.getColumnIndex("cDishHelpCode"))+";";
					    		String cDishClass1 	= cursor.getString(cursor.getColumnIndex("cDishClass1"))+";";
					    		String cDishClass2 	= cursor.getString(cursor.getColumnIndex("cDishClass2"))+";";
					    		String cDishUnitName= cursor.getString(cursor.getColumnIndex("cDishUnitName"))+";";
					    		String cDishUnitCode= cursor.getString(cursor.getColumnIndex("cDishUnitCode"))+";";
					    		String iDishStyle 	= cursor.getString(cursor.getColumnIndex("iDishStyle"))+";";
					    		String iDishDian 	= cursor.getString(cursor.getColumnIndex("iDishDian"))+";";
					    		String fDishPrice 	= cursor.getString(cursor.getColumnIndex("fDishPrice"))+";";

					    		String state = cDishName +cDishName2+cDishCode+cDishPinYin+cDishHelpCode
					    			+cDishClass1+cDishClass2+cDishUnitName+cDishUnitCode+iDishStyle+iDishDian+fDishPrice;
								fuffer = fuffer +","+ state;

					    		Log.i("info", "qqqq clude_all "+ "   "+state);			
				    		};
							
							OutputStream os = s.getOutputStream();
							os.write(( fuffer + "\n").getBytes("utf-8") );
						} catch (Exception e) {
							// TODO: handle exception
							System.out.println("qqqq_clude_all failed");
						}
					} 
					if (clomn[0].equals("qqqq_clude_table")) 
					{
						//命令方式是一开始同步桌台信息
						try {
				    		System.out.println("wl  select * from  lfcy_base_tableinf ");									
				    		Cursor  cursor = db.rawQuery("select * from lfcy_base_tableinf ", null);
				    		String  fuffer = "0" ;
				    		while (cursor.moveToNext()) {				    		
					    		String	iTableNumber	= cursor.getString(cursor.getColumnIndex("iTableNumber"))+";";	
					    		String	iTableClass 	= cursor.getString(cursor.getColumnIndex("iTableClass"))+";";	
					    		String	iTableClass2 	= cursor.getString(cursor.getColumnIndex("iTableClass2"))+";";
					    		String	iTableState 	= cursor.getString(cursor.getColumnIndex("iTableState"))+";";
					    		String	iTabletime 		= cursor.getString(cursor.getColumnIndex("iTabletime"))+";";
					    		if(iTabletime.equals(";") || iTabletime == null){//会抛出异常
					    			iTabletime = "null"+";";
						    		System.out.println("iTabletime = null");			
					    		}
					    		String	iTablePerson 	= cursor.getString(cursor.getColumnIndex("iTablePerson"))+";";
					    		String	iTable_Person	= cursor.getString(cursor.getColumnIndex("iTable_Person"))+";";
					    		if(iTable_Person.equals(";") || iTable_Person == null){//会抛出异常
					    			iTable_Person = "null"+";";
						    		System.out.println("iTable_Person = null");			
					    		}							
					    		String state = iTableNumber +iTableClass+iTableClass2+iTableState+iTabletime+iTablePerson+iTable_Person;
								fuffer = fuffer +","+ state;

					    		System.out.println("qqqq clude_all_table "+ "   "+state);			
				    		};

							OutputStream os = s.getOutputStream();
							os.write(( fuffer + "\n").getBytes("utf-8") );
						} catch (Exception e) {
							// TODO: handle exception
							System.out.println("qqqq clude_all_table failed");
						}
					} 
					if (clomn[0].equals("qqqq_get_table_opennum")) 
					{
						//命令方式是获取开台单号
						String line = clomn[1];
						Log.i("info","table_num = "+ line);
				   		String openNum = get_table_sellnum(line);	
						Log.i("info","table_num = "+ openNum);
						try {
							OutputStream os = s.getOutputStream();
							os.write(( openNum + "\n").getBytes("utf-8") );
							Log.i("info",openNum);
						} catch (Exception e) {
							// TODO: handle exception
							Log.i("info","qqqq_get_table_opennum failed ");							
						}
						
					} 
					if (clomn[0].equals("qqqq_yidian_cai")) 
					{
						//命令方式是获取已点菜
					} 
					if (clomn[0].equals("qqqq_newdiain_cai")) 
					{
						//命令方式是获取新增菜
					}
					if (clomn[0].equals("qqqq_clear_newsellinf")) 
					{
						//命令方式是发数据库实现清台同步
					}
					if (clomn[0].equals("qqqq_update_lfcy_base_sellinf_new")) 
					{
						//命令方式是发数据库实现清台同步
					}
					if (clomn[0].equals("qqqq_clude_bigclass")) 
					{
						//命令方式是获取大类
						try {
				    		System.out.println("wl  select * from  lfcy_base_bigsort ");									
				    		Cursor  cursor = db.rawQuery("select * from lfcy_base_bigsort ", null);
				    		String  fuffer = "0" ;
				    		while (cursor.moveToNext()) {				    		
					    		String	cName	= cursor.getString(cursor.getColumnIndex("cName"))+";";	
					    		String	cCode 	= cursor.getString(cursor.getColumnIndex("cCode"))+";";	
					    		String	cMemo 	= cursor.getString(cursor.getColumnIndex("cMemo"))+";";
					    		if(cMemo.equals(";") || cMemo == null){//会抛出异常
					    			cMemo = "null"+";";
						    		System.out.println("cMemo = null");			
					    		}							
					    		String state = cName +cCode+cMemo;
								fuffer = fuffer +","+ state;

					    		System.out.println("qqqq lfcy_base_bigsort "+ "   "+state);			
				    		};

							OutputStream os = s.getOutputStream();
							os.write(( fuffer + "\n").getBytes("utf-8") );
						} catch (Exception e) {
							// TODO: handle exception
							System.out.println("qqqq lfcy_base_bigsort failed");
						}
					}
					if (clomn[0].equals("qqqq_clude_smallclass")) 
					{
						//命令方式是获取小类
						try {
				    		System.out.println("wl  select * from  lfcy_base_smallsort ");									
				    		Cursor  cursor = db.rawQuery("select * from lfcy_base_smallsort ", null);
				    		String  fuffer = "0" ;
				    		while (cursor.moveToNext()) {				    		
					    		String	cName	= cursor.getString(cursor.getColumnIndex("cName"))+";";	
					    		String	cCode 	= cursor.getString(cursor.getColumnIndex("cCode"))+";";	
					    		String	cMemo 	= cursor.getString(cursor.getColumnIndex("cMemo"))+";";
					    		if(cMemo.equals(";") || cMemo == null){//会抛出异常
					    			cMemo = "null"+";";
						    		System.out.println("cMemo = null");			
					    		}							
					    		String state = cName +cCode+cMemo;
								fuffer = fuffer +","+ state;

					    		System.out.println("qqqq lfcy_base_bigsort "+ "   "+state);			
				    		};

							OutputStream os = s.getOutputStream();
							os.write(( fuffer + "\n").getBytes("utf-8") );
						} catch (Exception e) {
							// TODO: handle exception
							System.out.println("qqqq lfcy_base_smallsort failed");
						}
					}
					if (clomn[0].equals("qqqq_clude_tabletype")) 
					{
						//命令方式是获取桌台类型
						try
						{
				    		System.out.println("wl  select * from  lfcy_base_tabletype ");									
				    		Cursor  cursor = db.rawQuery("select * from lfcy_base_tabletype ", null);
				    		String  fuffer = "0" ;
				    		while (cursor.moveToNext()) {				    		
					    		String	cName	= cursor.getString(cursor.getColumnIndex("cName"))+";";	
					    		String	cCode 	= cursor.getString(cursor.getColumnIndex("cCode"))+";";	
					    		String	cMemo 	= cursor.getString(cursor.getColumnIndex("cMemo"))+";";
					    		if(cMemo.equals(";") || cMemo == null){//会抛出异常
					    			cMemo = "null"+";";
						    		System.out.println("cMemo = null");			
					    		}							
					    		String state = cName +cCode+cMemo;
								fuffer = fuffer +","+ state;
	
					    		System.out.println("qqqq lfcy_base_tabletype "+ "   "+state);			
				    		};
	
							OutputStream os = s.getOutputStream();
							os.write(( fuffer + "\n").getBytes("utf-8") );
						} catch (Exception e) {
							// TODO: handle exception
							System.out.println("qqqq lfcy_base_tabletype failed");
						}
					}					
					Message msg = new Message();
					msg.what = 0x123;
					msg.obj = content;
					handler.sendMessage(msg);
					Log.i("info", "write = "+ content);
				}
			} catch (Exception e) {
				// TODO: handle exception
				e.printStackTrace();
			}
		}

		private String readFromClient() {
			// TODO Auto-generated method stub
			try {
				String get = br.readLine();
				Log.i("info","read = " + get);
				return get;
			} catch (Exception e) {
				// TODO: handle exception
				Log.i("info","============================= remove ");
				Login.socketList.remove(s);
			}
			return null;
		}

	}
	/***************/
}